//円環リストを作る
function circleArray(base_array, index){
    var circle_index = index % base_array.length;
    if (index >= 0) {
        return base_array[circle_index];
    }
    else {
        var reverse_array = base_array.reverse();
        circle_index = (index + 1) % reverse_array.length;
        return reverse_array[circle_index];
    }

}

//円環配列の指定した場所から,d離れた値までの合計
function sumDeltaTheta(difference_focus_and_target, d, array){

    var start_position = mod(difference_focus_and_target, array.length);
    var circle_index_map = [0, 3, 2, 1];
    var circle_index = circle_index_map[start_position];
    var sum = 0.0;
    if (d >= 0) {
        for (var i = 0; i < d; i++) {
            sum += circleArray(array, circle_index % 4 + i);
        }
    }
    else {
        for (var j = 1; j <= Math.abs(d); j++) {
            sum -= circleArray(array, circle_index % 4 - j);
        }
    }
    return sum;
}

//負の値でも使える %
function mod(m, n){
    if (m >= 0) {
        return m % n;
    }
    else {
        if (m + n >= 0) {
            return m + n;
        }
        else {
            return mod(m + n, n);
        }
    }
}

//アニメーション中かどうかを表す
function wait(flag, func, timer){
    var _flag = flag;
    var _func = func;
    var _timer = timer;

}

//テキストをn文字ごとに分割した配列を返す
function sliceString(text, n){
    var text_size = text.length;
    var return_array = [];
    var tmp_text = text;
    while (text_size > 0) {
        var push_text = tmp_text.substring(0, n);
        return_array.push(push_text);
        tmp_text = tmp_text.substring(n);
        text_size -= n;
    }
    return return_array;

}

//角が丸い四角形を作る
function curvyCornerFillRect(x, y, width, height, corner, stroke_flag){
    if (!corner) {
        corner = 7;
    }
    ctx.beginPath();
    ctx.moveTo(x, y + corner);
    ctx.lineTo(x, y + height - corner);
    ctx.quadraticCurveTo(x, y + height, x + corner, y + height);
    ctx.lineTo(x + width - corner, y + height);
    ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - corner);
    ctx.lineTo(x + width, y + corner);
    ctx.quadraticCurveTo(x + width, y, x + width - corner, y);
    ctx.lineTo(x + corner, y);
    ctx.quadraticCurveTo(x, y, x, y + corner);
    ctx.fill();
    if (stroke_flag) {
        ctx.stroke();
    }
}

//For debug
function l(obj){
    console.log(obj);
}

function debug(){
    console.log("debug");
}

//中心を0,0とした座標から、実際の座標へ置き換える
function x(x){
    return x + settings.width / 2;
}

function y(y){
    return -1 * y + settings.height / 2;
}

//対数螺旋の式より、座標を決定
function spiral_x(theta){
    return 100 * Math.pow(1.1, theta) * Math.cos(theta);
}

function spiral_y(theta){
    return 100 * Math.pow(1.1, theta) * Math.sin(theta);
}

function get_hold_ids_str(){
    //axisesより、holdしている軸を調べ、stringにしてサーバに送ることのできる文字列にする
    var hold_axes = [];
    var send_hold_axes = "";
    jQuery.each(axises,function(i,axis){
        if (axis.hold) {
            hold_axes.push(axis.aid);
        }
        if (hold_axes.length != 0) {
            send_hold_axes = hold_axes.join("_");
        }

    });
    return send_hold_axes;
}

function get_focus_axis_id(){
    //focus軸ID
    var focus_axis_no;
    jQuery.each(axises, function(i, axis){
        if(axis.focus){
            focus_axis_no = axis.axis_no;
        }
    });
    return focus_axis_no;
}

//書籍詳細を表示する
function display_bookinfo(cell){

    logger.click_cells_log(cell.data.cid);

    //中心セルの内容を下部に表示する処理
    $("#bookinfo .content #bookimage a").attr("href",cell.data.detail).attr("target","_blank").unbind().bind("click", function(){ logger.click_bookinfo_log(cell.data.cid); });
    //.click(function() {console.log("send")});
    $("#bookinfo .content #bookimage a img").attr("src",cell.data.image_url);
    $("#bookinfo .content h3").html(cell.data.body);
    $("#bookinfo .content .price").html("￥"+ cell.data.price);
    $("#bookinfo .content .author").html(cell.data.author);
    $("#bookinfo .content .publisher").html(cell.data.publisher);
    $("#bookinfo .content .sales_rank").html(cell.data.sales_rank + "位");
    $("#bookinfo .content .publication_date").html(cell.data.publication_date);
    $("#bookinfo .content .genre").html(cell.data.genre);
    $("#bookinfo .content #booklink a").attr("href",cell.data.detail).attr("target","_blank").unbind().bind("click", function(){ logger.click_bookinfo_log(cell.data.cid); });
    $("#bookinfo .content #description").html("");
    $.ajax({
        url: "top/description",
        cache: false,
        data: "cid=" + cell.data.cid,
        success: function(text){
            $("#bookinfo .content #description").html(text);
        }
    });
}

//ダイアログを表示する
function display_dialog(message){
    //画面全体を半透明のシートで覆う
    ctx.fillStyle =  'rgba(0,0,0,0.2)';
    curvyCornerFillRect(0,0,settings.width,settings.height,0);
    
    //ダイアログを出す
    var dialog_width = 250;
    var dialog_height = 50;
    
    ctx.fillStyle =  'rgba(0,0,0,0.7)';
    ctx.strokeStyle =  'rgb(240,240,240)';
    curvyCornerFillRect(30,settings.height - 70,dialog_width,dialog_height,14,false);

    //テキスト表示
    ctx.fillStyle = 'rgb(255,255,255)';
    //ctx.font = "14px 'sans serif'";
    ctx.font = "25px 'monospace'";
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'left';
    if(message == "" || message == undefined){
        message = "ロード中";
    }
    ctx.fillText(message,60,settings.height - 45);
}

//軸をn本作り、cellを投入する
function display_obj(recieve_data){
    //console.log(recieve_data);
    var tmp_axises = new Array;
    var focus_position_theta = 3 / 4 * Math.PI;
    //ToDo:計算で角度を求める
    var theta = [Math.PI * 3 / 2, Math.PI + Math.atan(settings.height / settings.width), Math.PI, Math.PI - Math.atan(settings.height / settings.width), Math.PI / 2, Math.atan(settings.height / settings.width), 0];
    var colors = ['rgb(127,255,127)', 'rgb(255,191,127)', 'rgb(127,127,255)', 'rgb(100,100,100)'];
    var focus_position = 0;
    jQuery.each(recieve_data, function(i, val){
        if (val.is_focus) {
            focus_position = i;
        }
    });
    jQuery.each(recieve_data, function(i, val){
        //最初の１軸はタイムライン用
        //                if(i==0){

        //                }else{
        var tmp_axis = new Zzaxis(val.axisid, val.axisbody);
        tmp_axis.cells = [];
        //                    var theta_index = i - 1 - focus_position;
        var theta_index = i - focus_position;

        //第二引数は変数thetaにおけるfocus位置の場所を加える（Math.PI - Math.atan(settings.height / settings.width)はtheta[3]）
        tmp_axis.theta = circleArray(theta, theta_index + 3);
        tmp_axis.to_theta = circleArray(theta, theta_index + 3);
        tmp_axis.axis_no = i;
        if (theta_index == 0) {
            tmp_axis.focus = true;
        }
        if ((theta_index == 0 || theta_index == 1) || theta_index == 2) {
            tmp_axis.display = true;
        }
	
        var color = 'rgb(' + val.color[0] + ',' + val.color[1] + ',' + val.color[2] + ')';
        //255をこえないように場合分けしたい
        var sicklycolor = 'rgb(' + (val.color[0]+50) + ',' + (val.color[1]+50) + ',' + (val.color[2]+50) + ')';
        tmp_axis.color = color;
        tmp_axis.sicklycolor = sicklycolor;
        tmp_axis.hold = val.hold;
        //背景色
        //tmp_axis.sicklycolor = 'rgb(251,255,241)';
        var contents = val.data;
        //valを並びかえる
        var cells = new Array;
        cells[0] = contents[2];
        cells[1] = contents[1];
        cells[2] = contents[3];
        cells[3] = contents[0];
        cells[4] = contents[4];
        var center_val = cells.shift();
        var center_cell = new Zzcell(center_val.cid, center_val.body, center_val.image, center_val.detail,center_val.sales_rank, center_val.total_reviews, center_val.average_rating, center_val.price, center_val.number_ofpages,center_val.number_ofclicks, center_val.publication_date, center_val.author, center_val.genre, center_val.publisher);
        center_cell.x = x(0);
        center_cell.y = y(0);
        center_cell.axis = tmp_axis;
        center_cell.is_center = true;
		    
        if (theta_index == 0) {
            center_cell.display = true;
           
            display_bookinfo(center_cell);
        }
        else {
            center_cell.display = true;
        }
        tmp_axis.addcell(center_cell);
        jQuery.each(cells, function(j, val2){
            var cell = new Zzcell(val2.cid, val2.body, val2.image, val2.detail,val2.sales_rank, val2.total_reviews, val2.average_rating, val2.price, val2.number_ofpages, val2.number_ofclicks, val2.publication_date, val2.author ,val2.genre, val2.publisher);
            // cellに値を代入してゆく
            var cell_x = 100 * Math.pow(1.1, tmp_axis.theta + Math.PI * j) * Math.cos(tmp_axis.theta + Math.PI * j);
            var cell_y = 100 * Math.pow(1.1, tmp_axis.theta + Math.PI * j) * Math.sin(tmp_axis.theta + Math.PI * j);
            cell.x = x(cell_x);
            cell.y = y(cell_y);
            cell.axis = tmp_axis;
            tmp_axis.addcell(cell);
        });
        tmp_axises.push(tmp_axis);
    //                }
    });


    //AxisSymbolを作る
    var axis_size = tmp_axises.length;
    var center_position = [settings.width - 65, settings.height / 2];
    var h = 25;
    var w = 90;
    var m = 5;
    var position;
    var tmp_axis_symbols = [];
    jQuery.each(tmp_axises, function(i, axis){
        if ((axis_size % 2) == 0) {
            //偶数
            position = [center_position[0], center_position[1] + (i - axis_size / 2 + 1 / 2) * (m + h)];
        //console.log(position);
        }
        else {
            //奇数
            position = [center_position[0], center_position[1] + (2 * i + 1 - axis_size) * (h + m) / 2];

        }
        if (i == focus_position) {
            tmp_axis_symbols.push(new AxisSymbol(axis, [position[0], position[1]], w, h));
        }
        else {
            tmp_axis_symbols.push(new AxisSymbol(axis, [position[0], position[1]], w - 5, h - 5));
        }
    });
    axis_symbols = tmp_axis_symbols;

    //AxisBoardを作る
    var tmp_axis_boards = [];
    var center_xy = [settings.width / 2, 40];
    var distance_from_center = settings.width / 3;
    var focus_xy = [center_xy[0] - distance_from_center, center_xy[1]];
    var local_x = focus_xy[0];
    jQuery.each(tmp_axises, function(i, axis){
        if ((i == focus_position || i == focus_position + 1) || i == focus_position + 2) {
            tmp_axis_boards.push(new AxisBoard([local_x, focus_xy[1]], axis));
            local_x += distance_from_center;
        }
    });
    axis_boards = tmp_axis_boards;

    //表示順序の関係で、最後に表示されるように変更
    for (var j = 0; j < focus_position; j++) {
        var top_value = tmp_axises.pop();
        tmp_axises.push(top_value);
    }
    tmp_axises = tmp_axises.reverse();


    //アニメーションが終わるまで待機
    var timer = 100;
    timerID = setInterval(function(){
        var moving = (!cell_moving && !axis_moving);
        if (eval(moving)) {
            clearInterval(timerID);
            timerID = null;
            //アニメーションが終わり、取得した軸を表示
            axises = tmp_axises;
            can_mouse_wheel = true;
            //console.log(axises);
	    //console.log("finish!!");
	    //AxisOrderに入力
	    axis_order = [];
	    jQuery.each(axises, function(i, axis){
			    axis_order.push(axis.aid);
			});
	    axis_order = axis_order.reverse();
	    //console.log(axis_order);
        }
			  }, timer);
}
